#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

// 递归获取所有 JavaScript 文件
async function getJsFiles(dir) {
  const files = await readdir(dir);
  const jsFiles = [];

  for (const file of files) {
    const filePath = path.join(dir, file);
    const stats = await stat(filePath);

    if (stats.isDirectory() && !file.startsWith('.') && file !== 'node_modules') {
      jsFiles.push(...(await getJsFiles(filePath)));
    } else if (file.endsWith('.js')) {
      jsFiles.push(filePath);
    }
  }

  return jsFiles;
}

// 修复可选链操作符
async function fixOptionalChaining(filePath) {
  try {
    const content = await readFile(filePath, 'utf8');
    // 修复可选链操作符
    const fixedContent = content.replace(/\) \? \.([a-zA-Z])/g, ')?.$1');
    
    if (content !== fixedContent) {
      await writeFile(filePath, fixedContent, 'utf8');
      console.log(`Fixed: ${filePath}`);
      return true;
    }
    return false;
  } catch (error) {
    console.error(`Error processing ${filePath}:`, error);
    return false;
  }
}

// 主函数
async function main() {
  const rootDir = process.argv[2] || '.';
  console.log(`Scanning directory: ${rootDir}`);
  
  const jsFiles = await getJsFiles(rootDir);
  console.log(`Found ${jsFiles.length} JavaScript files`);
  
  let fixedCount = 0;
  for (const file of jsFiles) {
    const fixed = await fixOptionalChaining(file);
    if (fixed) fixedCount++;
  }
  
  console.log(`Fixed ${fixedCount} files`);
}

main().catch(console.error);